import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface Product {
  id: string
  name: string
  description: string
  category: string
  price: number
  originalPrice?: number
  image: string
  images?: string[]
  features: string[]
  specifications: Record<string, any>
  status: 'active' | 'inactive' | 'coming-soon'
  tags: string[]
  rating: number
  reviewCount: number
  createdAt: string
  updatedAt: string
}

export interface ProductCategory {
  id: string
  name: string
  description: string
  icon?: string
  parentId?: string
  children?: ProductCategory[]
  productCount: number
}

export interface ProductFilter {
  category?: string
  priceRange?: [number, number]
  tags?: string[]
  status?: string
  rating?: number
  search?: string
}

export interface ProductSort {
  field: 'name' | 'price' | 'rating' | 'createdAt' | 'updatedAt'
  order: 'asc' | 'desc'
}

export const useProductStore = defineStore('product', () => {
  // 状态
  const products = ref<Product[]>([])
  const categories = ref<ProductCategory[]>([])
  const currentProduct = ref<Product | null>(null)
  const loading = ref(false)
  const searchLoading = ref(false)
  const filter = ref<ProductFilter>({})
  const sort = ref<ProductSort>({ field: 'createdAt', order: 'desc' })
  const pagination = ref({
    page: 1,
    pageSize: 12,
    total: 0
  })
  
  // 计算属性
  const filteredProducts = computed(() => {
    let result = [...products.value]
    
    // 应用筛选条件
    if (filter.value.category) {
      result = result.filter(product => product.category === filter.value.category)
    }
    
    if (filter.value.priceRange) {
      const [min, max] = filter.value.priceRange
      result = result.filter(product => product.price >= min && product.price <= max)
    }
    
    if (filter.value.tags && filter.value.tags.length > 0) {
      result = result.filter(product => 
        filter.value.tags!.some(tag => product.tags.includes(tag))
      )
    }
    
    if (filter.value.status) {
      result = result.filter(product => product.status === filter.value.status)
    }
    
    if (filter.value.rating) {
      result = result.filter(product => product.rating >= filter.value.rating!)
    }
    
    if (filter.value.search) {
      const searchTerm = filter.value.search.toLowerCase()
      result = result.filter(product => 
        product.name.toLowerCase().includes(searchTerm) ||
        product.description.toLowerCase().includes(searchTerm) ||
        product.tags.some(tag => tag.toLowerCase().includes(searchTerm))
      )
    }
    
    // 应用排序
    result.sort((a, b) => {
      const { field, order } = sort.value
      let aValue = a[field]
      let bValue = b[field]
      
      if (typeof aValue === 'string') {
        aValue = aValue.toLowerCase()
        bValue = (bValue as string).toLowerCase()
      }
      
      if (order === 'asc') {
        return aValue < bValue ? -1 : aValue > bValue ? 1 : 0
      } else {
        return aValue > bValue ? -1 : aValue < bValue ? 1 : 0
      }
    })
    
    return result
  })
  
  const paginatedProducts = computed(() => {
    const start = (pagination.value.page - 1) * pagination.value.pageSize
    const end = start + pagination.value.pageSize
    return filteredProducts.value.slice(start, end)
  })
  
  const totalPages = computed(() => {
    return Math.ceil(filteredProducts.value.length / pagination.value.pageSize)
  })
  
  const productsByCategory = computed(() => {
    const result: Record<string, Product[]> = {}
    products.value.forEach(product => {
      if (!result[product.category]) {
        result[product.category] = []
      }
      result[product.category].push(product)
    })
    return result
  })
  
  const featuredProducts = computed(() => {
    return products.value
      .filter(product => product.tags.includes('featured'))
      .slice(0, 8)
  })
  
  const popularProducts = computed(() => {
    return products.value
      .filter(product => product.rating >= 4.5)
      .sort((a, b) => b.reviewCount - a.reviewCount)
      .slice(0, 6)
  })
  
  // 方法
  const setProducts = (newProducts: Product[]) => {
    products.value = newProducts
    pagination.value.total = newProducts.length
  }
  
  const setCategories = (newCategories: ProductCategory[]) => {
    categories.value = newCategories
  }
  
  const setCurrentProduct = (product: Product | null) => {
    currentProduct.value = product
  }
  
  const setFilter = (newFilter: Partial<ProductFilter>) => {
    filter.value = { ...filter.value, ...newFilter }
    pagination.value.page = 1 // 重置到第一页
  }
  
  const clearFilter = () => {
    filter.value = {}
    pagination.value.page = 1
  }
  
  const setSort = (newSort: ProductSort) => {
    sort.value = newSort
    pagination.value.page = 1
  }
  
  const setPagination = (newPagination: Partial<typeof pagination.value>) => {
    pagination.value = { ...pagination.value, ...newPagination }
  }
  
  // 获取产品列表
  const fetchProducts = async (params?: {
    category?: string
    page?: number
    pageSize?: number
    search?: string
  }): Promise<void> => {
    try {
      loading.value = true
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 800))
      
      // 模拟产品数据
      const mockProducts: Product[] = [
        {
          id: '1',
          name: 'IKeyERP企业版',
          description: '全功能企业资源规划系统，支持财务、人事、供应链等模块',
          category: 'erp',
          price: 299999,
          originalPrice: 399999,
          image: '/product-erp.jpg',
          images: ['/product-erp-1.jpg', '/product-erp-2.jpg'],
          features: ['财务管理', '人力资源', '供应链管理', '生产管理'],
          specifications: {
            '部署方式': '云端/本地',
            '用户数量': '不限',
            '存储空间': '1TB起',
            '技术支持': '7x24小时'
          },
          status: 'active',
          tags: ['featured', 'enterprise', 'erp'],
          rating: 4.8,
          reviewCount: 156,
          createdAt: '2024-01-01T00:00:00.000Z',
          updatedAt: '2024-01-15T00:00:00.000Z'
        },
        {
          id: '2',
          name: 'IKeyCRM客户管理',
          description: '智能客户关系管理系统，提升销售效率和客户满意度',
          category: 'crm',
          price: 199999,
          image: '/product-crm.jpg',
          features: ['客户管理', '销售管道', '营销自动化', '数据分析'],
          specifications: {
            '部署方式': '云端',
            '用户数量': '500人以内',
            '存储空间': '500GB',
            '集成能力': '支持API'
          },
          status: 'active',
          tags: ['popular', 'crm', 'sales'],
          rating: 4.6,
          reviewCount: 89,
          createdAt: '2024-01-02T00:00:00.000Z',
          updatedAt: '2024-01-16T00:00:00.000Z'
        },
        {
          id: '3',
          name: 'IKeyBI商业智能',
          description: '强大的数据分析和可视化平台，助力数据驱动决策',
          category: 'bi',
          price: 159999,
          image: '/product-bi.jpg',
          features: ['数据可视化', '报表生成', '预测分析', '实时监控'],
          specifications: {
            '数据源': '多种数据库',
            '报表类型': '50+种图表',
            '并发用户': '200人',
            '更新频率': '实时'
          },
          status: 'active',
          tags: ['analytics', 'bi', 'visualization'],
          rating: 4.7,
          reviewCount: 67,
          createdAt: '2024-01-03T00:00:00.000Z',
          updatedAt: '2024-01-17T00:00:00.000Z'
        },
        {
          id: '4',
          name: 'IKeyOA办公自动化',
          description: '现代化办公自动化系统，提升团队协作效率',
          category: 'oa',
          price: 99999,
          image: '/product-oa.jpg',
          features: ['流程审批', '文档管理', '考勤管理', '项目协作'],
          specifications: {
            '用户数量': '1000人以内',
            '存储空间': '200GB',
            '移动端': '支持APP',
            '集成': '钉钉/企微'
          },
          status: 'active',
          tags: ['office', 'collaboration', 'workflow'],
          rating: 4.5,
          reviewCount: 134,
          createdAt: '2024-01-04T00:00:00.000Z',
          updatedAt: '2024-01-18T00:00:00.000Z'
        },
        {
          id: '5',
          name: 'IKeyHR人力资源',
          description: '全面的人力资源管理系统，从招聘到离职全流程管理',
          category: 'hr',
          price: 129999,
          image: '/product-hr.jpg',
          features: ['招聘管理', '薪酬管理', '绩效考核', '培训管理'],
          specifications: {
            '员工数量': '5000人以内',
            '薪酬计算': '自动化',
            '报表': '30+种',
            '合规性': '符合法规'
          },
          status: 'active',
          tags: ['hr', 'recruitment', 'payroll'],
          rating: 4.4,
          reviewCount: 78,
          createdAt: '2024-01-05T00:00:00.000Z',
          updatedAt: '2024-01-19T00:00:00.000Z'
        },
        {
          id: '6',
          name: 'IKeyCloud云平台',
          description: '企业级云计算平台，提供安全可靠的云服务',
          category: 'cloud',
          price: 299999,
          image: '/product-cloud.jpg',
          features: ['云服务器', '数据库', '存储服务', '安全防护'],
          specifications: {
            '可用性': '99.9%',
            '扩展性': '弹性伸缩',
            '安全等级': '等保三级',
            '备份': '多地备份'
          },
          status: 'coming-soon',
          tags: ['cloud', 'infrastructure', 'security'],
          rating: 0,
          reviewCount: 0,
          createdAt: '2024-01-06T00:00:00.000Z',
          updatedAt: '2024-01-20T00:00:00.000Z'
        }
      ]
      
      setProducts(mockProducts)
    } catch (error) {
      console.error('Fetch products failed:', error)
    } finally {
      loading.value = false
    }
  }
  
  // 获取产品分类
  const fetchCategories = async (): Promise<void> => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))
      
      const mockCategories: ProductCategory[] = [
        {
          id: 'erp',
          name: 'ERP系统',
          description: '企业资源规划系统',
          icon: 'Setting',
          productCount: 1
        },
        {
          id: 'crm',
          name: 'CRM系统',
          description: '客户关系管理系统',
          icon: 'User',
          productCount: 1
        },
        {
          id: 'bi',
          name: 'BI系统',
          description: '商业智能分析系统',
          icon: 'DataAnalysis',
          productCount: 1
        },
        {
          id: 'oa',
          name: 'OA系统',
          description: '办公自动化系统',
          icon: 'Document',
          productCount: 1
        },
        {
          id: 'hr',
          name: 'HR系统',
          description: '人力资源管理系统',
          icon: 'Avatar',
          productCount: 1
        },
        {
          id: 'cloud',
          name: '云平台',
          description: '企业云计算平台',
          icon: 'CloudUpload',
          productCount: 1
        }
      ]
      
      setCategories(mockCategories)
    } catch (error) {
      console.error('Fetch categories failed:', error)
    }
  }
  
  // 获取产品详情
  const fetchProductById = async (id: string): Promise<Product | null> => {
    try {
      loading.value = true
      
      // 先从本地查找
      let product = products.value.find(p => p.id === id)
      
      if (!product) {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 600))
        // 这里应该调用API获取产品详情
        product = products.value.find(p => p.id === id) || null
      }
      
      setCurrentProduct(product || null)
      return product || null
    } catch (error) {
      console.error('Fetch product failed:', error)
      return null
    } finally {
      loading.value = false
    }
  }
  
  // 搜索产品
  const searchProducts = async (query: string): Promise<Product[]> => {
    try {
      searchLoading.value = true
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 400))
      
      const searchTerm = query.toLowerCase()
      const results = products.value.filter(product => 
        product.name.toLowerCase().includes(searchTerm) ||
        product.description.toLowerCase().includes(searchTerm) ||
        product.tags.some(tag => tag.toLowerCase().includes(searchTerm))
      )
      
      return results
    } catch (error) {
      console.error('Search products failed:', error)
      return []
    } finally {
      searchLoading.value = false
    }
  }
  
  // 获取相关产品
  const getRelatedProducts = (productId: string, limit: number = 4): Product[] => {
    const product = products.value.find(p => p.id === productId)
    if (!product) return []
    
    return products.value
      .filter(p => p.id !== productId && p.category === product.category)
      .slice(0, limit)
  }
  
  // 初始化产品数据
  const initializeProducts = async (): Promise<void> => {
    await Promise.all([
      fetchProducts(),
      fetchCategories()
    ])
  }
  
  // 重置产品状态
  const resetProducts = () => {
    products.value = []
    categories.value = []
    currentProduct.value = null
    loading.value = false
    searchLoading.value = false
    filter.value = {}
    sort.value = { field: 'createdAt', order: 'desc' }
    pagination.value = {
      page: 1,
      pageSize: 12,
      total: 0
    }
  }
  
  return {
    // 状态
    products,
    categories,
    currentProduct,
    loading,
    searchLoading,
    filter,
    sort,
    pagination,
    
    // 计算属性
    filteredProducts,
    paginatedProducts,
    totalPages,
    productsByCategory,
    featuredProducts,
    popularProducts,
    
    // 方法
    setProducts,
    setCategories,
    setCurrentProduct,
    setFilter,
    clearFilter,
    setSort,
    setPagination,
    fetchProducts,
    fetchCategories,
    fetchProductById,
    searchProducts,
    getRelatedProducts,
    initializeProducts,
    resetProducts
  }
})